package com.doge.walknovel.business.home.library

import com.doge.walknovel.api.model.NovelInfo
import com.doge.walknovel.core.account.AccountHelper.self
import com.doge.walknovel.utils.*
import java.io.*

object LibraryCacheHelper {
    private val novelsDir: File get() {
        return File(appContext.externalCacheDir, "myLib${self.memberId}").apply {
            if (!exists()) mkdirs()
        }
    }
    private val cacheFile: File get() = File(novelsDir, "data").apply {
        if (parentFile?.exists() != true) parentFile?.mkdirs()
        if (!exists()) createNewFile()
    }

    fun saveCache(data: List<NovelInfo>) = runOnIO {
        val file = cacheFile
        FileUtils.write(file, toJson(data))
    }

    fun loadCache(): String? {
        require(!isMainThread())
        val file = cacheFile
        return FileUtils.read(file)
    }
}